package com.yklx.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;

public class JwtUtil {

    private final Key signingKey;
    private final Long expiration;

    public JwtUtil(String secret, Long expiration) {
        // 对于HS512算法，需要至少512位(64字节)的密钥
        byte[] secretBytes = secret.getBytes();
        if (secretBytes.length < 64) {
            // 创建一个足够长的字节数组
            byte[] extendedSecret = new byte[64];
            // 重复原始密钥直到填满64字节
            for (int i = 0; i < extendedSecret.length; i++) {
                extendedSecret[i] = secretBytes[i % secretBytes.length];
            }
            this.signingKey = Keys.hmacShaKeyFor(extendedSecret);
        } else {
            // 如果原始密钥已经足够长，直接使用
            this.signingKey = Keys.hmacShaKeyFor(secretBytes);
        }
        this.expiration = expiration;
    }

    // 生成JWT token
    public String generateToken(String userId, String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration * 1000);

        return Jwts.builder()
                .setSubject(userId)  // 使用userId作为subject
                .claim("username", username)
                .setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .signWith(signingKey, SignatureAlgorithm.HS512) // 使用HS512算法
                .compact();
    }

    // 从JWT token中获取用户ID
    public String getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(signingKey)
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    // 从JWT token中获取用户名
    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(signingKey)
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims.get("username", String.class);
    }

    // 验证JWT token
    public Boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(signingKey)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            System.out.println("JWT验证失败: " + e.getMessage());
            return false;
        }
    }
}